#coding=utf-8

import web
import datetime

import config

class ctModel():
	def __init__(self):
		try:
			self.db = web.database(dbn='mysql', user=config.USER, pw=config.PASSWD, db=config.NAME)
		except:
			return 

	#获取所有文章
	def get_posts(self):
		return db.select('entries', order = 'id DESC')
		
	#获取文章内容
	def get_td_item(self,id):
		try:
			return db.select('entries', where = 'id=$id', vars = locals())[0]
		except IndexError:
			return None
	#新建课表数据
	def new_ct_data(self,ct_id,data):
		for y in data:
			for x in data[y]:
				for class_item in data[y][x]:
					item = data[y][x][class_item]
					if len(item)>1:
						item_id = self.new_ct_item(item)
						self.db.insert('ct_data',
							ct_id = ct_id,
							tb_y = y,
							tb_x = x,
							item_id = item_id,
							week_d = item['week_d'],
							class_n = item['class_n'])
	#添加课表项
	def new_ct_item(self,item):
		try:
			result = self.db.select('ct_item', where = "title='"+item['title']+"' AND teacher='"+item['teacher']+"' AND week_s='"+item['week_s']+"' AND week_e='"+item['week_e']+"' AND addr='"+item['addr']+"' AND exam_addr='"+item['exam_addr']+"' AND exam_time='"+item['exam_time']+"';", what="id")[0]
			return result['id']
		except IndexError:
			return 	self.db.insert('ct_item',
				title = item['title'],
				teacher = item['teacher'],
				week_s = item['week_s'],
				week_e = item['week_e'],
				addr = item['addr'],
				exam_addr = item['exam_addr'],
				exam_time = item['exam_time'])
	#删除文章
	def del_post(self,id):
		db.delete('entries', where = 'id = $id', vars = locals())
		posted_on = datetime.datetime.utcnow()
	#修改文章
	def update_post(self,id, title, text):
		db.update('entries',
			where = 'id = $id',
			vars = locals(),
			title = title,
			content = text)